﻿HmJS.$Import('core.element');

/*
---
version: 0.1.1-0
description: Converts local image to greyscale version, original code from http://www.ajaxblender.com/howto-convert-image-to-grayscale-using-javascript.html
license: MIT-style
download: http://mootools.net/forge/p/image_togreyscale
source: http://github.com/ninjapenguin/mootools-img.toGreyscale/
demo: http://ninjapenguin.github.com/demos/imageToGreyscale/

authors:
- Matthew Wells

requires:
- core/1.2.4:*

provides: [Image.toGreyscale]
...
*/

HmJS.register('image.effect.Greyscale', function ($ns) {

	var Greyscale = {
		convert: function (element) {
			if (element.get('original_src')) { return element; }

			var canvas = document.createElement('canvas');
			var canvasContext = canvas.getContext('2d');

			var imgW = element.width;
			var imgH = element.height;
			canvas.width = imgW;
			canvas.height = imgH;
			canvasContext.drawImage(element, 0, 0);

			var imgPixels = canvasContext.getImageData(0, 0, imgW, imgH);

			var h = imgPixels.height,
					w = imgPixels.width,
					data = imgPixels.data;
			for (var y = 0; y < h; y++) {
				for (var x = 0; x < w; x++) {
					var i = (y * 4) * w + x * 4;
					var avg = (data[i] + data[i + 1] + data[i + 2]) / 3;
					data[i] = avg;
					data[i + 1] = avg;
					data[i + 2] = avg;
				}
			}
			canvasContext.putImageData(imgPixels, 0, 0, 0, 0, w, h);

			url = canvas.toDataURL();

			var el = $(element);
			el.set('original_src', el.get('src'));
			el.set('greyscale_src', url);
			el.set('src', url);
			return element;
		}
	};

	Element.implement({

		toGreyscale: function () {
			if (this.get('tag') != 'img') { return element; }

			if (Browser.ie) {
				return this.style.filter = 'progid:DXImageTransform.Microsoft.BasicImage(grayScale=1)';
			} else {
				if (!!document.createElement('canvas').getContext) {
					if (this.get('greyscale_src')) {
						return this.set('src', this.get('greyscale_src'));
					} else {
						return Greyscale.convert(this);
					}
				}
				return this;
			}
		},

		toSaturated: function () {
			if (this.get('tag') != 'img') { return element; }

			if (Browser.ie) {
				return this.style.filter = '';
			} else {
				if (!!document.createElement('canvas').getContext && this.get('original_src')) {
					return this.set('src', this.get('original_src'));
				}
				return this;
			}
		}

	});

	return Greyscale;
});